class Document < ActiveRecord::Base
  belongs_to :folder, :counter_cache => true
  belongs_to :user
  
  @@PIC_SUFFIX = %w{png gif jpg jpeg tiff bmp}
  
  def move_to_folder(new_folder_id)
    new_folder = Folder.find(new_folder_id)
    check_same_name(self.user_id, self.folder_id, self.name)
    self.folder = new_folder
  end
  
  def  delete!
    self.flag = "deleted"
    self.update
  end
  
  def rename(new_name)
    self.name = new_name
    self.update
  end
  
  def self.all_documents_size(user_id)
    Document.sum(:size, :conditions => ["flag != 'deleted' AND user_id = ?", user_id])
  end
  
  def self.has_same_name(user_id, folder_id, name)
    doc = Document.find(:first, :conditions => ["flag != 'deleted' AND user_id = ? AND folder_id =? AND name = ?", user_id, folder_id, name])
    !doc.nil?
  end
  
  def self.is_picture(suffix)
    @@PIC_SUFFIX.index(suffix.downcase) != nil
  end
  
  private
  def check_same_name(user_id, folder_id, name)
    if Document.has_same_name(user_id, folder_id, name)
      self.name = self.name + "_1"
      check_same_name(user_id, folder_id, self.name)
    else
      self.update
    end
  end
end
